package com.eclipse.e0113_网络编程.socket_文件下载;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileServer {

	public static void main(String[] args) throws Exception {
		
		//连接
		ServerSocket serverSocket = new ServerSocket(9001);
		Socket socket = serverSocket.accept();

		OutputStream outputStream = socket.getOutputStream();
		InputStream inputStream = socket.getInputStream();

		// 读取g盘下的文件名
		File gPan = new File("/Users/liuzhuangzhuang/iotest");

		//文件名
		String[] fileNames = gPan.list();

		// 发送可下载的文件名给客户端
		for (String fileName : fileNames) {
			outputStream.write((fileName + "\r\n").getBytes());
			
		}
		outputStream.write(("\r\n").getBytes());

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

		//读取客户端要下载的文件名
		String downFileName = bufferedReader.readLine();
		//把文件内容给她
		byte[] fileContent = Files.readAllBytes(Paths.get("/Users/liuzhuangzhuang/iotest/" + downFileName));

		outputStream.write(fileContent);

		outputStream.close();
		socket.close();
	}
}
